import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:uuid/uuid.dart';
import '../models/models.dart';
import '../data/mock_data.dart';
import 'database_service.dart';
import 'hive_service.dart';

/// 音乐库管理服务类
/// 负责扫描本地音乐文件、管理音乐库和提供搜索功能
class MusicLibraryService extends ChangeNotifier {
  static final MusicLibraryService _instance = MusicLibraryService._internal();
  factory MusicLibraryService() => _instance;
  MusicLibraryService._internal();

  final DatabaseService _databaseService = DatabaseService();
  final HiveService _hiveService = HiveService();
  final Uuid _uuid = const Uuid();

  // 音乐库状态
  List<Music> _musicLibrary = [];
  List<Playlist> _playlists = [];
  bool _isScanning = false;
  bool _isLoading = false;
  String _scanProgress = '';
  int _totalFiles = 0;
  int _scannedFiles = 0;

  // 支持的音频格式
  static const List<String> _supportedFormats = [
    '.mp3',
    '.m4a',
    '.aac',
    '.wav',
    '.flac',
    '.ogg',
    '.wma',
  ];

  /// 初始化音乐库服务
  Future<void> init() async {
    if (kIsWeb) {
      // Web平台初始化
      debugPrint('Web平台音乐库服务初始化');
      _musicLibrary = [];
      _playlists = [];
      notifyListeners();
      return;
    }
    
    await _loadMusicLibrary();
    await _loadPlaylists();
  }

  /// 扫描本地音乐文件
  Future<void> scanLocalMusic() async {
    if (_isScanning) return;

    try {
      _isScanning = true;
      _scanProgress = '正在请求存储权限...';
      notifyListeners();

      // 请求存储权限
      final permission = await _requestStoragePermission();
      if (!permission) {
        _scanProgress = '存储权限被拒绝';
        _isScanning = false;
        notifyListeners();
        return;
      }

      _scanProgress = '正在扫描音乐文件...';
      notifyListeners();

      // 获取音乐目录
      final musicDirectories = await _getMusicDirectories();
      
      // 扫描音乐文件
      final musicFiles = <FileSystemEntity>[];
      for (final directory in musicDirectories) {
        if (await directory.exists()) {
          final files = await _scanDirectory(directory);
          musicFiles.addAll(files);
        }
      }

      _totalFiles = musicFiles.length;
      _scannedFiles = 0;
      
      if (_totalFiles == 0) {
        _scanProgress = '未找到音乐文件';
        _isScanning = false;
        notifyListeners();
        return;
      }

      _scanProgress = '正在解析音乐信息...';
      notifyListeners();

      // 解析音乐文件信息
      final newMusicList = <Music>[];
      for (final file in musicFiles) {
        try {
          final music = await _parseAudioFile(file);
          if (music != null) {
            newMusicList.add(music);
          }
        } catch (e) {
          debugPrint('解析音乐文件失败: ${file.path}, 错误: $e');
        }
        
        _scannedFiles++;
        _scanProgress = '正在解析音乐信息... ($_scannedFiles/$_totalFiles)';
        notifyListeners();
      }

      // 保存到数据库
      _scanProgress = '正在保存到数据库...';
      notifyListeners();
      
      await _saveMusicToDatabase(newMusicList);
      await _loadMusicLibrary();

      _scanProgress = '扫描完成，共找到 ${newMusicList.length} 首音乐';
      
    } catch (e) {
      _scanProgress = '扫描失败: $e';
      debugPrint('扫描音乐失败: $e');
    } finally {
      _isScanning = false;
      notifyListeners();
    }
  }

  /// 请求存储权限
  Future<bool> _requestStoragePermission() async {
    if (Platform.isAndroid) {
      final status = await Permission.storage.request();
      return status.isGranted;
    } else if (Platform.isIOS) {
      // iOS不需要特殊权限访问音乐库
      return true;
    }
    return false;
  }

  /// 获取音乐目录
  Future<List<Directory>> _getMusicDirectories() async {
    final directories = <Directory>[];
    
    try {
      if (Platform.isAndroid) {
        // Android音乐目录
        directories.addAll([
          Directory('/storage/emulated/0/Music'),
          Directory('/storage/emulated/0/Download'),
          Directory('/sdcard/Music'),
          Directory('/sdcard/Download'),
        ]);
        
        // 外部存储目录
        final externalDir = await getExternalStorageDirectory();
        if (externalDir != null) {
          directories.add(Directory('${externalDir.path}/Music'));
        }
      } else if (Platform.isIOS) {
        // iOS文档目录
        final documentsDir = await getApplicationDocumentsDirectory();
        directories.add(Directory('${documentsDir.path}/Music'));
      } else if (kIsWeb) {
        // web平台不支持本地文件系统访问
        debugPrint('web平台不支持本地文件系统访问');
        return directories;
      }
      
      // 应用文档目录（web平台会跳过此部分）
      if (!kIsWeb) {
        final appDocDir = await getApplicationDocumentsDirectory();
        directories.add(Directory('${appDocDir.path}/Music'));
      }
      
    } catch (e) {
      debugPrint('获取音乐目录失败: $e');
    }
    
    return directories;
  }

  /// 扫描目录中的音乐文件
  Future<List<FileSystemEntity>> _scanDirectory(Directory directory) async {
    final musicFiles = <FileSystemEntity>[];
    
    try {
      await for (final entity in directory.list(recursive: true)) {
        if (entity is File && _isSupportedAudioFile(entity.path)) {
          musicFiles.add(entity);
        }
      }
    } catch (e) {
      debugPrint('扫描目录失败: ${directory.path}, 错误: $e');
    }
    
    return musicFiles;
  }

  /// 检查是否为支持的音频文件
  bool _isSupportedAudioFile(String filePath) {
    final extension = filePath.toLowerCase().substring(filePath.lastIndexOf('.'));
    return _supportedFormats.contains(extension);
  }

  /// 解析音频文件信息
  Future<Music?> _parseAudioFile(FileSystemEntity file) async {
    try {
      final fileStat = await file.stat();
      final fileName = file.path.split('/').last;
      final nameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
      
      // 简单解析文件名（实际项目中可以使用metadata_god等库获取详细信息）
      final parts = nameWithoutExtension.split(' - ');
      String title = nameWithoutExtension;
      String artist = '未知艺术家';
      
      if (parts.length >= 2) {
        artist = parts[0].trim();
        title = parts[1].trim();
      }
      
      return Music(
        id: _uuid.v4(),
        title: title,
        artist: artist,
        album: '未知专辑',
        filePath: file.path,
        duration: 0, // 需要使用音频库获取实际时长
        fileSize: fileStat.size,
        coverArt: null,
        genre: null,
        year: null,
        bitRate: null,
        sampleRate: null,
        isFavorite: false,
        playCount: 0,
        createdAt: DateTime.now(),
        updatedAt: fileStat.modified,
      );
    } catch (e) {
      debugPrint('解析音频文件失败: ${file.path}, 错误: $e');
      return null;
    }
  }

  /// 保存音乐到数据库
  Future<void> _saveMusicToDatabase(List<Music> musicList) async {
    try {
      for (final music in musicList) {
        await _databaseService.insertMusic(music);
        await _hiveService.saveMusic(music);
      }
    } catch (e) {
      debugPrint('保存音乐到数据库失败: $e');
    }
  }

  /// 获取所有音乐
  Future<List<Music>> getAllMusic() async {
    try {
      return await _databaseService.getAllMusic();
    } catch (e) {
      debugPrint('获取音乐失败: $e');
      return [];
    }
  }

  /// 加载音乐库
  Future<void> _loadMusicLibrary() async {
    try {
      _isLoading = true;
      notifyListeners();
      
      _musicLibrary = await _databaseService.getAllMusic();
      
      // 如果音乐库为空，添加默认音乐数据
      if (_musicLibrary.isEmpty) {
        debugPrint('音乐库为空，添加默认音乐数据...');
        final mockMusicList = MockData.getMockMusicList();
        
        // 保存默认音乐到数据库
        for (final music in mockMusicList) {
          await _databaseService.insertMusic(music);
          await _hiveService.saveMusic(music);
        }
        
        // 重新加载音乐库
        _musicLibrary = await _databaseService.getAllMusic();
        debugPrint('已添加 ${mockMusicList.length} 首默认音乐');
      }
      
    } catch (e) {
      debugPrint('加载音乐库失败: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 加载播放列表
  Future<void> _loadPlaylists() async {
    try {
      _playlists = await _databaseService.getAllPlaylists();
      
      // 如果播放列表为空，添加默认播放列表数据
      if (_playlists.isEmpty) {
        debugPrint('播放列表为空，添加默认播放列表数据...');
        final mockPlaylists = MockData.getMockPlaylists();
        
        // 保存默认播放列表到数据库
        for (final playlist in mockPlaylists) {
          await _databaseService.insertPlaylist(playlist);
        }
        
        // 重新加载播放列表
        _playlists = await _databaseService.getAllPlaylists();
        debugPrint('已添加 ${mockPlaylists.length} 个默认播放列表');
      }
      
      notifyListeners();
    } catch (e) {
      debugPrint('加载播放列表失败: $e');
    }
  }

  /// 搜索音乐
  Future<List<Music>> searchMusic(String query) async {
    if (query.trim().isEmpty) {
      return _musicLibrary;
    }
    
    try {
      return await _databaseService.searchMusic(query);
    } catch (e) {
      debugPrint('搜索音乐失败: $e');
      return [];
    }
  }

  /// 按艺术家分组
  Map<String, List<Music>> getMusicByArtist() {
    final Map<String, List<Music>> artistMap = {};
    
    for (final music in _musicLibrary) {
      final artist = music.artist.isEmpty ? '未知艺术家' : music.artist;
      artistMap.putIfAbsent(artist, () => []).add(music);
    }
    
    return artistMap;
  }

  /// 按专辑分组
  Map<String, List<Music>> getMusicByAlbum() {
    final Map<String, List<Music>> albumMap = {};
    
    for (final music in _musicLibrary) {
      final album = music.album?.isEmpty == true ? '未知专辑' : music.album!;
      albumMap.putIfAbsent(album, () => []).add(music);
    }
    
    return albumMap;
  }

  /// 获取收藏的音乐
  List<Music> getFavoriteMusic() {
    return _musicLibrary.where((music) => music.isFavorite).toList();
  }

  /// 获取最近播放的音乐
  List<Music> getRecentlyPlayed() {
    final recentMusic = _musicLibrary
        .where((music) => music.playCount > 0)
        .toList();
    
    recentMusic.sort((a, b) => 
        b.updatedAt.compareTo(a.updatedAt));
    
    return recentMusic.take(20).toList();
  }

  /// 获取最常播放的音乐
  List<Music> getMostPlayed() {
    final playedMusic = _musicLibrary
        .where((music) => music.playCount > 0)
        .toList();
    
    playedMusic.sort((a, b) => b.playCount.compareTo(a.playCount));
    
    return playedMusic.take(20).toList();
  }

  /// 切换收藏状态
  Future<void> toggleFavorite(Music music) async {
    try {
      final updatedMusic = music.copyWith(isFavorite: !music.isFavorite);
      await _databaseService.updateMusic(updatedMusic);
      await _hiveService.saveMusic(updatedMusic);
      
      // 更新本地列表
      final index = _musicLibrary.indexWhere((m) => m.id == music.id);
      if (index != -1) {
        _musicLibrary[index] = updatedMusic;
        notifyListeners();
      }
    } catch (e) {
      debugPrint('切换收藏状态失败: $e');
    }
  }

  /// 创建播放列表
  Future<Playlist?> createPlaylist(String name, {String? description}) async {
    try {
      final playlist = Playlist(
        id: _uuid.v4(),
        name: name,
        description: description,
        coverImage: null,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        musicIds: [],
        isDefault: false,
      );
      
      await _databaseService.insertPlaylist(playlist);
      _playlists.add(playlist);
      notifyListeners();
      
      return playlist;
    } catch (e) {
      debugPrint('创建播放列表失败: $e');
      return null;
    }
  }

  /// 添加音乐到播放列表
  Future<void> addMusicToPlaylist(String playlistId, String musicId) async {
    try {
      final playlistIndex = _playlists.indexWhere((p) => p.id == playlistId);
      if (playlistIndex == -1) return;
      
      final playlist = _playlists[playlistIndex];
      final updatedMusicIds = List<String>.from(playlist.musicIds);
      
      if (!updatedMusicIds.contains(musicId)) {
        updatedMusicIds.add(musicId);
        
        final updatedPlaylist = playlist.copyWith(
          musicIds: updatedMusicIds,
          updatedAt: DateTime.now(),
        );
        
        await _databaseService.insertPlaylist(updatedPlaylist);
        _playlists[playlistIndex] = updatedPlaylist;
        notifyListeners();
      }
    } catch (e) {
      debugPrint('添加音乐到播放列表失败: $e');
    }
  }

  /// 从播放列表移除音乐
  Future<void> removeMusicFromPlaylist(String playlistId, String musicId) async {
    try {
      final playlistIndex = _playlists.indexWhere((p) => p.id == playlistId);
      if (playlistIndex == -1) return;
      
      final playlist = _playlists[playlistIndex];
      final updatedMusicIds = List<String>.from(playlist.musicIds);
      updatedMusicIds.remove(musicId);
      
      final updatedPlaylist = playlist.copyWith(
        musicIds: updatedMusicIds,
        updatedAt: DateTime.now(),
      );
      
      await _databaseService.insertPlaylist(updatedPlaylist);
      _playlists[playlistIndex] = updatedPlaylist;
      notifyListeners();
    } catch (e) {
      debugPrint('从播放列表移除音乐失败: $e');
    }
  }

  /// 获取播放列表中的音乐
  List<Music> getPlaylistMusic(String playlistId) {
    final playlist = _playlists.firstWhere(
      (p) => p.id == playlistId,
      orElse: () => Playlist(
        id: '',
        name: '',
        description: null,
        coverImage: null,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        musicIds: [],
        isDefault: false,
      ),
    );
    
    if (playlist.id.isEmpty) return [];
    
    return playlist.musicIds
        .map((id) => _musicLibrary.firstWhere(
              (music) => music.id == id,
              orElse: () => Music(
                id: '',
                title: '',
                artist: '',
                album: null,
                filePath: '',
                duration: 0,
                fileSize: 0,
                coverArt: null,
                genre: null,
                year: null,
                bitRate: null,
                sampleRate: null,
                isFavorite: false,
                playCount: 0,
                createdAt: DateTime.now(),
                updatedAt: DateTime.now(),
              ),
            ))
        .where((music) => music.id.isNotEmpty)
        .toList();
  }

  /// 刷新音乐库
  Future<void> refreshLibrary() async {
    await _loadMusicLibrary();
    await _loadPlaylists();
  }

  /// 清空音乐库
  Future<void> clearLibrary() async {
    try {
      await _databaseService.clearTable('music');
      await _hiveService.clearMusicCache();
      _musicLibrary.clear();
      notifyListeners();
    } catch (e) {
      debugPrint('清空音乐库失败: $e');
    }
  }

  // Getters
  List<Music> get musicLibrary => List.unmodifiable(_musicLibrary);
  List<Playlist> get playlists => List.unmodifiable(_playlists);
  bool get isScanning => _isScanning;
  bool get isLoading => _isLoading;
  String get scanProgress => _scanProgress;
  int get totalFiles => _totalFiles;
  int get scannedFiles => _scannedFiles;
  int get musicCount => _musicLibrary.length;
  int get playlistCount => _playlists.length;
  int get favoriteCount => getFavoriteMusic().length;

  /// 检查音乐是否被收藏
  bool isFavorite(String id) {
    final music = _musicLibrary.firstWhere(
      (m) => m.id == id,
      orElse: () => Music(
        id: '',
        title: '',
        artist: '',
        filePath: '',
        duration: 0,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      ),
    );
    return music.id.isNotEmpty ? music.isFavorite : false;
  }

  /// 添加到收藏
  Future<void> addFavorite(String musicId) async {
    final music = _musicLibrary.firstWhere(
      (m) => m.id == musicId,
      orElse: () => Music(
        id: '',
        title: '',
        artist: '',
        filePath: '',
        duration: 0,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      ),
    );
    
    if (music.id.isNotEmpty && !music.isFavorite) {
      await toggleFavorite(music);
    }
  }

  /// 从收藏移除
  Future<void> removeFavorite(String musicId) async {
    final music = _musicLibrary.firstWhere(
      (m) => m.id == musicId,
      orElse: () => Music(
        id: '',
        title: '',
        artist: '',
        filePath: '',
        duration: 0,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
      ),
    );
    
    if (music.id.isNotEmpty && music.isFavorite) {
      await toggleFavorite(music);
    }
  }
}